<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/21 下午5:11
 * +-------------------------------------------------------------
 */

namespace app\common\traits;

use app\Request;
use think\captcha\facade\Captcha;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;
use think\response\Json;
use app\admin\service\annotation\NodeAnnotation;

trait LoginTrait
{
    /**
     * @NodeAnnotation (title="用户登录")
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(Request $request): Json
    {
        $post = $request->post();
        if(!$this->sceneValidate($post, 'admin_login')) return $this->errorJson($this->msg);
        $admin = $this->model->where(['username' => $post['username']])->find();
        if (empty($admin)) {
            return $this->errorJson('用户不存在');
        }
        if (password($post['password']) != $admin->password) {
            return $this->errorJson('密码输入有误');
        }
        if ($admin->status == 0) {
            return $this->errorJson('账号已被禁用');
        }
        $admin->login_num += 1;
        $admin->save();
        $admin = $admin->toArray();
        unset($admin['password']);
        $admin['expire_time'] = $post['keep_login'] == 1 ? true : time() + 7200;
        session($this->appName, $admin);
        return $this->successJson('登录成功');
    }

    /**
     * @NodeAnnotation (title="退出", description="退出", node="admin_out")
     */
    public function out(): Json
    {
        session($this->appName, null);
        return $this->successJson('退出成功');
    }

    /**
     * 验证码
     * @return Response
     */
    public function captcha(): Response
    {
        return Captcha::instance()->create();
    }
}